package com.example.pro1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.example.adapter.MyAdapter;
import com.example.json.Contacts;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ListViewActivity extends Activity {
	private ListView lv_json;
	private List<Contacts> mlist;
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				mlist=(List<Contacts>) msg.obj;
				MyAdapter myAdapter=new MyAdapter(ListViewActivity.this,mlist);
				lv_json.setAdapter(myAdapter);
				break;
			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_view);
		initLayout();
		setLayout();
	}

	private void setLayout() {
		OkHttpClient client=new OkHttpClient();
		Request request=new Request.Builder()
									.url("http://176.122.140.84/contact.json")
									.build();
		client.newCall(request).enqueue(new Callback() {
			
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				List<Contacts> list=new ArrayList<Contacts>();
				String json=arg1.body().string();
				Gson gson=new Gson();
				list= gson.fromJson(json,new TypeToken<List<Contacts>>(){}.getType());
				Message message=new Message();
				message.obj=list;
				message.what=1;
				handler.sendMessage(message);
			}
			
			@Override
			public void onFailure(Call arg0, IOException arg1) {
				
			}
		});
	}

	private void initLayout() {
		lv_json=(ListView) findViewById(R.id.lv_json);
	}
}
